<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户管理 - 物联网平台</title>
    
    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    
    <!-- FontAwesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <!-- 自定义样式 -->
    <style>
        .fade-in {
            animation: fadeIn 0.3s ease-in-out;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .table-row-hover:hover {
            background-color: #f8fafc;
            transform: scale(1.01);
            transition: all 0.2s ease-in-out;
        }
        
        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
        
        .btn-success {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
        }
        
        .btn-danger {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
        }
    </style>
</head>
<body class="bg-gray-50 font-sans">
    <div class="max-w-7xl mx-auto fade-in">
        <!-- 页面标题 -->
        <div class="mb-8">
            <div class="flex items-center justify-between">
                <div>
                    <h1 class="text-3xl font-bold text-gray-900 mb-2">用户管理</h1>
                    <p class="text-gray-600">管理系统用户，设置权限和角色</p>
                </div>
                <div class="flex space-x-3">
                    <button onclick="exportUsers()" class="inline-flex items-center px-4 py-2 border border-gray-300 rounded-lg shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-colors">
                        <i class="fas fa-download mr-2"></i>
                        导出Excel
                    </button>
                    <button onclick="showAddUserModal()" class="inline-flex items-center px-4 py-2 border border-transparent rounded-lg shadow-sm text-sm font-medium text-white btn-primary hover:opacity-90 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-all">
                        <i class="fas fa-plus mr-2"></i>
                        添加用户
                    </button>
                </div>
            </div>
        </div>
        
        <!-- 搜索和筛选区域 -->
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 mb-6">
            <div class="flex flex-col md:flex-row md:items-center md:justify-between space-y-4 md:space-y-0">
                <div class="flex-1 max-w-md">
                    <div class="relative">
                        <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                            <i class="fas fa-search text-gray-400"></i>
                        </div>
                        <input type="text" id="searchKeyword" placeholder="搜索用户名、真实姓名、邮箱或手机号" 
                               class="block w-full pl-10 pr-3 py-2 border border-gray-300 rounded-lg leading-5 bg-white placeholder-gray-500 focus:outline-none focus:placeholder-gray-400 focus:ring-1 focus:ring-blue-500 focus:border-blue-500">
                    </div>
                </div>
                <div class="flex items-center space-x-3">
                    <button onclick="searchUsers()" class="inline-flex items-center px-4 py-2 border border-transparent rounded-lg shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-colors">
                        <i class="fas fa-search mr-2"></i>
                        搜索
                    </button>
                    <button onclick="clearSearch()" class="inline-flex items-center px-4 py-2 border border-gray-300 rounded-lg shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-colors">
                        <i class="fas fa-times mr-2"></i>
                        清除
                    </button>
                </div>
            </div>
        </div>
        
        <!-- 用户列表 -->
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">用户信息</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">联系方式</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">创建时间</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                        </tr>
                    </thead>
                    <tbody id="userTableBody" class="bg-white divide-y divide-gray-200">
                        <!-- 用户数据将通过JavaScript动态加载 -->
                    </tbody>
                </table>
            </div>
            
            <!-- 分页 -->
            <div class="bg-white px-4 py-3 flex items-center justify-between border-t border-gray-200 sm:px-6">
                <div class="flex-1 flex justify-between sm:hidden">
                    <button onclick="loadUsers(currentPage - 1)" class="relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">
                        上一页
                    </button>
                    <button onclick="loadUsers(currentPage + 1)" class="ml-3 relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">
                        下一页
                    </button>
                </div>
                <div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
                    <div>
                        <p class="text-sm text-gray-700">
                            显示第 <span class="font-medium">1</span> 到 <span class="font-medium">10</span> 条，共 <span class="font-medium" id="totalRecords">0</span> 条记录
                        </p>
                    </div>
                    <div>
                        <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px" id="pagination">
                            <!-- 分页按钮将通过JavaScript动态生成 -->
                        </nav>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 添加/编辑用户模态框 -->
    <div id="userModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full hidden z-50">
        <div class="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
            <div class="mt-3">
                <div class="flex items-center justify-between mb-4">
                    <h3 class="text-lg font-medium text-gray-900" id="modalTitle">添加用户</h3>
                    <button onclick="closeUserModal()" class="text-gray-400 hover:text-gray-600">
                        <i class="fas fa-times text-xl"></i>
                    </button>
                </div>
                
                <form id="userForm" class="space-y-4">
                    <input type="hidden" id="userId">
                    
                    <div>
                        <label for="userName" class="block text-sm font-medium text-gray-700 mb-1">用户名 *</label>
                        <input type="text" id="userName" required 
                               class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500">
                    </div>
                    
                    <div>
                        <label for="realName" class="block text-sm font-medium text-gray-700 mb-1">真实姓名</label>
                        <input type="text" id="realName" 
                               class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500">
                    </div>
                    
                    <div>
                        <label for="userEmail" class="block text-sm font-medium text-gray-700 mb-1">邮箱</label>
                        <input type="email" id="userEmail" 
                               class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500">
                    </div>
                    
                    <div>
                        <label for="userMobile" class="block text-sm font-medium text-gray-700 mb-1">手机号</label>
                        <input type="text" id="userMobile" 
                               class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500">
                    </div>
                    
                    <div>
                        <label for="userStatus" class="block text-sm font-medium text-gray-700 mb-1">状态</label>
                        <select id="userStatus" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500">
                            <option value="1">正常</option>
                            <option value="0">禁用</option>
                        </select>
                    </div>
                    
                    <div id="passwordGroup">
                        <label for="userPassword" class="block text-sm font-medium text-gray-700 mb-1">密码 *</label>
                        <input type="password" id="userPassword" 
                               class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500">
                    </div>
                </form>
                
                <div class="flex justify-end space-x-3 mt-6">
                    <button onclick="closeUserModal()" class="px-4 py-2 border border-gray-300 rounded-lg text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-colors">
                        取消
                    </button>
                    <button onclick="saveUser()" class="px-4 py-2 border border-transparent rounded-lg text-sm font-medium text-white btn-primary hover:opacity-90 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-all">
                        保存
                    </button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 删除确认模态框 -->
    <div id="deleteModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full hidden z-50">
        <div class="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
            <div class="mt-3 text-center">
                <div class="mx-auto flex items-center justify-center h-12 w-12 rounded-full bg-red-100 mb-4">
                    <i class="fas fa-exclamation-triangle text-red-600 text-xl"></i>
                </div>
                <h3 class="text-lg font-medium text-gray-900 mb-2">确认删除</h3>
                <p class="text-sm text-gray-500 mb-6">确定要删除这个用户吗？此操作不可恢复。</p>
                
                <div class="flex justify-center space-x-3">
                    <button onclick="closeDeleteModal()" class="px-4 py-2 border border-gray-300 rounded-lg text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-colors">
                        取消
                    </button>
                    <button onclick="confirmDelete()" class="px-4 py-2 border border-transparent rounded-lg text-sm font-medium text-white btn-danger hover:opacity-90 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 transition-all">
                        确定删除
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- JavaScript -->
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <script>
        let currentPage = 1;
        let pageSize = 10;
        let totalRecords = 0;
        let deleteUserId = null;
        
        // 页面加载完成后执行
        $(document).ready(function() {
            loadUsers();
        });
        
        // 加载用户列表
        function loadUsers(page = 1) {
            currentPage = page;
            const keyword = $('#searchKeyword').val();
            
            $.ajax({
                url: '/api/user/list',
                method: 'GET',
                data: {
                    current: currentPage,
                    size: pageSize,
                    keyword: keyword
                },
                success: function(response) {
                    if (response.code === 200) {
                        renderUserTable(response.data);
                        renderPagination(response.data);
                    } else {
                        showNotification('加载用户列表失败: ' + response.message, 'error');
                    }
                },
                error: function() {
                    showNotification('网络错误，请稍后重试', 'error');
                }
            });
        }
        
        // 渲染用户表格
        function renderUserTable(data) {
            const tbody = $('#userTableBody');
            tbody.empty();
            
            if (data.records && data.records.length > 0) {
                data.records.forEach(function(user) {
                    const row = `
                        <tr class="table-row-hover">
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div class="flex items-center">
                                    <div class="flex-shrink-0 h-10 w-10">
                                        <div class="h-10 w-10 rounded-full bg-blue-500 flex items-center justify-center">
                                            <i class="fas fa-user text-white"></i>
                                        </div>
                                    </div>
                                    <div class="ml-4">
                                        <div class="text-sm font-medium text-gray-900">${user.name || '-'}</div>
                                        <div class="text-sm text-gray-500">${user.realName || '-'}</div>
                                    </div>
                                </div>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div class="text-sm text-gray-900">${user.email || '-'}</div>
                                <div class="text-sm text-gray-500">${user.mobile || '-'}</div>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <span class="inline-flex px-2 py-1 text-xs font-semibold rounded-full ${user.status === 1 ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}">
                                    ${user.status === 1 ? '正常' : '禁用'}
                                </span>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                ${user.createTime || '-'}
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                <button onclick="editUser(${user.id})" class="text-blue-600 hover:text-blue-900 mr-3 transition-colors">
                                    <i class="fas fa-edit"></i> 编辑
                                </button>
                                <button onclick="deleteUser(${user.id})" class="text-red-600 hover:text-red-900 transition-colors">
                                    <i class="fas fa-trash"></i> 删除
                                </button>
                            </td>
                        </tr>
                    `;
                    tbody.append(row);
                });
            } else {
                tbody.append(`
                    <tr>
                        <td colspan="5" class="px-6 py-12 text-center text-gray-500">
                            <div class="flex flex-col items-center">
                                <i class="fas fa-users text-4xl text-gray-300 mb-3"></i>
                                <p class="text-lg">暂无用户数据</p>
                                <p class="text-sm">点击"添加用户"开始创建</p>
                            </div>
                        </td>
                    </tr>
                `);
            }
            
            totalRecords = data.total || 0;
            $('#totalRecords').text(totalRecords);
        }
        
        // 渲染分页
        function renderPagination(data) {
            const pagination = $('#pagination');
            pagination.empty();
            
            const totalPages = data.pages || 1;
            
            // 上一页
            const prevDisabled = currentPage <= 1 ? 'cursor-not-allowed opacity-50' : 'hover:bg-gray-50';
            pagination.append(`
                <button onclick="loadUsers(${currentPage - 1})" ${currentPage <= 1 ? 'disabled' : ''} 
                        class="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-500 ${prevDisabled}">
                    <i class="fas fa-chevron-left"></i>
                </button>
            `);
            
            // 页码
            for (let i = 1; i <= totalPages; i++) {
                if (i === currentPage) {
                    pagination.append(`
                        <span class="relative inline-flex items-center px-4 py-2 border border-blue-500 bg-blue-50 text-sm font-medium text-blue-600">
                            ${i}
                        </span>
                    `);
                } else {
                    pagination.append(`
                        <button onclick="loadUsers(${i})" 
                                class="relative inline-flex items-center px-4 py-2 border border-gray-300 bg-white text-sm font-medium text-gray-700 hover:bg-gray-50">
                            ${i}
                        </button>
                    `);
                }
            }
            
            // 下一页
            const nextDisabled = currentPage >= totalPages ? 'cursor-not-allowed opacity-50' : 'hover:bg-gray-50';
            pagination.append(`
                <button onclick="loadUsers(${currentPage + 1})" ${currentPage >= totalPages ? 'disabled' : ''} 
                        class="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500 ${nextDisabled}">
                    <i class="fas fa-chevron-right"></i>
                </button>
            `);
        }
        
        // 搜索用户
        function searchUsers() {
            loadUsers(1);
        }
        
        // 清除搜索
        function clearSearch() {
            $('#searchKeyword').val('');
            loadUsers(1);
        }
        
        // 显示添加用户模态框
        function showAddUserModal() {
            $('#modalTitle').text('添加用户');
            $('#userForm')[0].reset();
            $('#userId').val('');
            $('#passwordGroup').show();
            $('#userPassword').prop('required', true);
            $('#userModal').removeClass('hidden');
        }
        
        // 关闭用户模态框
        function closeUserModal() {
            $('#userModal').addClass('hidden');
        }
        
        // 编辑用户
        function editUser(userId) {
            $.ajax({
                url: `/api/user/${userId}`,
                method: 'GET',
                success: function(response) {
                    if (response.code === 200) {
                        const user = response.data;
                        $('#modalTitle').text('编辑用户');
                        $('#userId').val(user.id);
                        $('#userName').val(user.name);
                        $('#realName').val(user.realName);
                        $('#userEmail').val(user.email);
                        $('#userMobile').val(user.mobile);
                        $('#userStatus').val(user.status);
                        $('#passwordGroup').hide();
                        $('#userPassword').prop('required', false);
                        $('#userModal').removeClass('hidden');
                    } else {
                        showNotification('获取用户信息失败: ' + response.message, 'error');
                    }
                },
                error: function() {
                    showNotification('网络错误，请稍后重试', 'error');
                }
            });
        }
        
        // 保存用户
        function saveUser() {
            const userId = $('#userId').val();
            const userData = {
                name: $('#userName').val(),
                realName: $('#realName').val(),
                email: $('#userEmail').val(),
                mobile: $('#userMobile').val(),
                status: parseInt($('#userStatus').val())
            };
            
            if (userId) {
                // 编辑用户
                userData.id = userId;
                $.ajax({
                    url: '/api/user/update',
                    method: 'PUT',
                    contentType: 'application/json',
                    data: JSON.stringify(userData),
                    success: function(response) {
                        if (response.code === 200) {
                            closeUserModal();
                            loadUsers(currentPage);
                            showNotification('用户更新成功', 'success');
                        } else {
                            showNotification('用户更新失败: ' + response.message, 'error');
                        }
                    },
                    error: function() {
                        showNotification('网络错误，请稍后重试', 'error');
                    }
                });
            } else {
                // 添加用户
                userData.password = $('#userPassword').val();
                $.ajax({
                    url: '/api/user/add',
                    method: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(userData),
                    success: function(response) {
                        if (response.code === 200) {
                            closeUserModal();
                            loadUsers(1);
                            showNotification('用户添加成功', 'success');
                        } else {
                            showNotification('用户添加失败: ' + response.message, 'error');
                        }
                    },
                    error: function() {
                        showNotification('网络错误，请稍后重试', 'error');
                    }
                });
            }
        }
        
        // 删除用户
        function deleteUser(userId) {
            deleteUserId = userId;
            $('#deleteModal').removeClass('hidden');
        }
        
        // 关闭删除模态框
        function closeDeleteModal() {
            $('#deleteModal').addClass('hidden');
        }
        
        // 确认删除
        function confirmDelete() {
            if (deleteUserId) {
                $.ajax({
                    url: `/api/user/delete/${deleteUserId}`,
                    method: 'DELETE',
                    success: function(response) {
                        if (response.code === 200) {
                            closeDeleteModal();
                            loadUsers(currentPage);
                            showNotification('用户删除成功', 'success');
                        } else {
                            showNotification('用户删除失败: ' + response.message, 'error');
                        }
                    },
                    error: function() {
                        showNotification('网络错误，请稍后重试', 'error');
                    }
                });
            }
        }
        
        // 导出用户数据
        function exportUsers() {
            window.open('/api/user/export', '_blank');
        }
        
        // 显示通知
        function showNotification(message, type = 'info') {
            // 这里可以实现一个简单的通知系统
            alert(message);
        }
    </script>
</body>
</html>
